#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024/3/23 22:30
# @File           : login_log.py
# @IDE            : PyCharm
# @Desc           : 登录日志依赖
from sqlalchemy.sql.expression import true, false
from starlette.requests import Request
from src.config import settings
from src.db.db_database import alchemy
from src.core.exception import BaseAppException
from src.services.login_record_service import LoginRecordService
from src.utils.toolsutils import ToolsUtils


class LoginLog:
    def __init__(self, login_type: str = "login"):
        self.login_type = login_type

    """登录日志依赖

    用于记录用户登录日志，包括登录状态、IP地址、设备信息等
    """

    async def __call__(self, request: Request):
        """记录登录日志

        Args:
            request: 请求对象

        Raises:
            BaseAppException: 业务异常
            Exception: 系统异常
        """
        message: str = "Success"
        status: bool = True
        err = None
        ip = ToolsUtils.get_ip_address(request)
        request.state.ipaddr = ip
        log_info = {}
        if settings.system.IP_RESOLVE_ENABLE:
            addr_info = ToolsUtils.get_location_offline(ip)
            request.state.address = addr_info["address"]
            log_info.update(addr_info)

        agent_info = ToolsUtils.get_agent_info(request)
        log_info.update(agent_info)

        try:
            yield
        except BaseAppException as e:
            message = e.msg
            status = False
            err = e
        except Exception as e:
            message = "系统错误"
            status = False
            err = e
        finally:
            await self._record_login_log(request, log_info, ip, status, message)

        if err is not None:
            raise err

    async def _record_login_log(
        self, request: Request, log_info: dict, ip: str, status: bool, message: str
    ) -> None:
        """记录登录日志

        Args:
            request: 请求对象
            ip: IP地址
            status: 登录状态
            message: 登录消息
        """
        username = getattr(request.state, "username", "")

        log = {
            "username": username,
            "status":"1" if status else "2",
            "message": message,
            "agent": request.headers.get("User-Agent")[:100],
            "login_type": self.login_type,
            "params": request.scope.get("body", ""),
            "ipaddr": ip,
        }
        log.update(log_info)
        async with alchemy.with_async_session() as db:
            await LoginRecordService(session=db).create(log, auto_commit=True)
